﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using BLL;
public partial class Report_SKU : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Check.CheckPermission("900200");
        if (!IsPostBack)
        {
            List<Model.ORDERFROM> lst = new BLL.ORDERFROM().GetAllList(false);
            string kwdm = ConfigurationManager.AppSettings["kwdm"];
            string cpkwdm = ConfigurationManager.AppSettings["cpkwdm"];

            //why 09-06-30
            if (kwdm == cpkwdm)
            {
                ListItem[] items1 ={new ListItem("全部","全部"),
                              new ListItem(kwdm,kwdm)};

                drpKW.Items.AddRange(items1);
            }
            else
            {
                ListItem[] items ={new ListItem("全部","全部"),
                              new ListItem(kwdm,kwdm),
                              new ListItem(cpkwdm,cpkwdm)};
                drpKW.Items.AddRange(items);
            }
            //add
            ORDER_OFCODE(); //加载订单来源
            Init_zdr();     
            ORDER_DTCODE(); //交易类型
            InitPayType();  //支付方式
            Init_Suggestion();//订单意见初始化

            txtSP.Attributes.Add("onclick", "SearchProduct_Report('../')");
        }
    }
    #region 订单来源
    private void ORDER_OFCODE()
    {/*
        List<Model.ORDERFROM> properties = new BLL.ORDERFROM().GetAllList();
        DDL_OrderFrom.DataSource = properties;
        DDL_OrderFrom.DataTextField = "OF_NAME";
        DDL_OrderFrom.DataValueField = "OF_CODE";
        DDL_OrderFrom.DataBind();
        ListItem li = new ListItem();
        li.Text = "全部";
        li.Value = "-1";
        DDL_OrderFrom.Items.Insert(0, li);
       */
    }
    #endregion
    #region 订单审核人/财务审核人/发货人/结算人初始化
    private void Init_zdr()
    {/*
        List<Model.USERS> lists = new BLL.USERS().GetList(null, "[USERS_STOP]=0", null);

        //订单审核人
        DDL_Checker.DataSource = lists;
        DDL_Checker.DataTextField = "Users_Name";
        DDL_Checker.DataValueField = "Users_Code";
        DDL_Checker.DataBind();

        //财务审核人
        DDL_aChecker.DataSource = lists;
        DDL_aChecker.DataTextField = "Users_Name";
        DDL_aChecker.DataValueField = "Users_Code";
        DDL_aChecker.DataBind();

        //发货审核人
        DDL_Sender.DataSource = lists;
        DDL_Sender.DataTextField = "Users_Name";
        DDL_Sender.DataValueField = "Users_Code";
        DDL_Sender.DataBind();

        //结算人
        DDL_Clearer.DataSource = lists;
        DDL_Clearer.DataTextField = "Users_Name";
        DDL_Clearer.DataValueField = "Users_Code";
        DDL_Clearer.DataBind();

        ListItem li = new ListItem();
        li.Value = "-1";
        li.Text = "选择";
        DDL_OrderCreater.Items.Insert(0, li);
        DDL_Checker.Items.Insert(0, li);
        DDL_aChecker.Items.Insert(0, li);
        DDL_Sender.Items.Insert(0, li);
        DDL_Clearer.Items.Insert(0, li);
      */
    }

    #endregion

    #region 交易类型
    private void ORDER_DTCODE()
    {/*
        List<Model.DEALTYPE> properties = new BLL.DEALTYPE().GetAllList();
        DDL_tradetype.DataSource = properties;
        DDL_tradetype.DataTextField = "DT_NAME";
        DDL_tradetype.DataValueField = "DT_CODE";
        DDL_tradetype.DataBind();
        ListItem li = new ListItem();
        li.Text = "全部";
        li.Value = "-1";
        DDL_tradetype.Items.Insert(0, li);*/
    }
    #endregion

    #region 支付方式初始化
    private void InitPayType()
    {/*
        //绑定支付方式
        List<Model.PAYTYPE> paytype = new List<Model.PAYTYPE>();
        paytype = new BLL.PAYTYPE().GetAllList();
        DDL_PayType.DataSource = paytype;
        DDL_PayType.DataTextField = "PT_NAME";
        DDL_PayType.DataValueField = "PT_CODE";
        DDL_PayType.DataBind();
        ListItem li = new ListItem();
        li.Text = "全部";
        li.Value = "-1";
        DDL_PayType.Items.Insert(0, li);*/
    }
    #endregion
    #region 订单意见
    private void Init_Suggestion()
    {/*
        DDL_ORDER_STATETYPECODE.DataSource = new BLL.STATETYPE().GetAllList();
        DDL_ORDER_STATETYPECODE.DataTextField = "ST_NAME";
        DDL_ORDER_STATETYPECODE.DataValueField = "ST_CODE";
        DDL_ORDER_STATETYPECODE.DataBind();

        ListItem li = new ListItem();
        li.Text = "全部";
        li.Value = "-1";
        DDL_ORDER_STATETYPECODE.Items.Insert(0, li);
    */
    }
    #endregion

    private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            e.Item.Cells[0].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
            e.Item.Cells[1].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
            e.Item.Cells[2].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
            e.Item.Cells[3].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
            e.Item.Cells[4].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
            e.Item.Cells[5].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
            //e.Item.Cells[3].Attributes.Add("style", "vnd.ms-excel.numberformat:￥#,###.00");
            
        }
    }
    protected void DataGrid_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
        e.Item.Cells[0].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
        e.Item.Cells[1].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
        e.Item.Cells[2].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
        e.Item.Cells[3].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
        e.Item.Cells[4].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
        e.Item.Cells[5].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
    }
    /// <summary>
    /// DataTable导出Excel
    /// </summary>
    /// <param name="dtData"></param>
    public   void DataTable2Excel(System.Data.DataTable dtData)
    {
        System.Web.UI.WebControls.DataGrid dgExport = null;
        System.Web.HttpContext curContext = System.Web.HttpContext.Current;
        System.IO.StringWriter strWriter = null;
        System.Web.UI.HtmlTextWriter htmlWriter = null;

        if (dtData != null)
        {
            curContext.Response.ContentType = "application/vnd.ms-excel";
            curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
            curContext.Response.Charset = "";

            dtData.Rows.RemoveAt(0);
            strWriter = new System.IO.StringWriter();
            htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);

            dgExport = new System.Web.UI.WebControls.DataGrid();

            //dtData.Columns.Add("发放状态");
            ////dtData.Columns.Add("财务审核");
            ////dtData.Columns.Add("结算");


            dtData.Columns["SPDM"].ColumnName = "款号";
            dtData.Columns["COLOR"].ColumnName = "颜色代码";
            dtData.Columns["COLORNAME"].ColumnName = "颜色";
            dtData.Columns["SIZE"].ColumnName = "尺码代码";
            dtData.Columns["SIZENAME"].ColumnName = "尺码";

            dtData.Columns["SPMC"].ColumnName = "商品名称";
            dtData.Columns["QTY"].ColumnName = "销售数量";
            dtData.Columns["AMT"].ColumnName = "占比（数量）";


            dtData.Columns["QTY_RATE"].ColumnName = "销售金额";
            dtData.Columns["AMT_RATE"].ColumnName = "占比（金额）";
            dtData.Columns["KW"].ColumnName = "仓库";
            dtData.Columns["SL"].ColumnName = "库存量";
            dtData.Columns["SL3"].ColumnName = "可用量";
            dtData.Columns["PERIOD"].ColumnName = "周转期";
            for (int i = 0; i < dtData.Rows.Count; i++)
            {
                //dtData.Rows[i]["发货/入库"] = dtData.Rows[i]["SendOrReceive"].ToString() == "1" ? "已发货" : "未发货"; 

                dtData.Rows[i]["款号"] = Convert.ToString(dtData.Rows[i]["款号"].ToString());//加"''"防止科 学计数法  ; "''" +
              

            }
            //////移除列
            //dtData.Columns.Remove(dtData.Columns["SENDFLAG"]); 

            //dgExport.DataSource = dtData.DefaultView;
            //dgExport.AllowPaging = false;
            //dgExport.DataBind();
            //dgExport.ItemDataBound += new DataGridItemEventHandler(DataGrid_ItemDataBound);
            ////OnItemDataBound="DataGrid_ItemDataBound"
            //           dgExport.RenderControl(htmlWriter);

            this.DataGrid.DataSource = dtData.DefaultView;
            this.DataGrid.AllowPaging = false;
            this.DataGrid.DataBind();
            this.DataGrid.RenderControl(htmlWriter);

            curContext.Response.Write(strWriter.ToString());
            curContext.Response.End();
        }
    } 


    protected void btnExport_Click(object sender, EventArgs e)
    {/*
        if ((Tbx_OrderCreateF.Text.Trim().Length < 1 || Tbx_OrderCreateT.Text.Trim().Length < 1) && (Tbx_AcheckDateF.Text.Trim().Length < 1 || Tbx_AcheckDateT.Text.Trim().Length < 1) && (Tbx_SendDateF.Text.Trim().Length < 1 || Tbx_SendDateT.Text.Trim().Length < 1))
        {
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert(\"请至少输入一个起止日期\")", true);
            return;
        }*/
        if (HttpContext.Current.Request.Form.Get("txtSP").Length > 8000)
        {
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert(\"选择产品过多,产品代码字符串长度之和不能超过8000字符\")", true);
            return;
        }
        try
        {
            Bind(1); //导出excel
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert(\"统计出错\")", true);
            return;
        }
    }


    protected void btnSearch_Click(object sender, EventArgs e)
    {/*
        if ((Tbx_OrderCreateF.Text.Trim().Length < 1 || Tbx_OrderCreateT.Text.Trim().Length < 1) && (Tbx_AcheckDateF.Text.Trim().Length < 1 || Tbx_AcheckDateT.Text.Trim().Length < 1) && (Tbx_SendDateF.Text.Trim().Length < 1 || Tbx_SendDateT.Text.Trim().Length < 1))
        {
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert(\"请至少输入一个起止日期\")", true);
            return;
        }*/
        if (HttpContext.Current.Request.Form.Get("txtSP").Length > 8000)
        {
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert(\"选择产品过多,产品代码字符串长度之和不能超过8000字符\")", true);
            return;
        }
        try
        {
            Bind(0);
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert(\"统计出错\")", true);
            return;
        }
    }
    private void Bind(int pageIndex)
    {
        if (HttpContext.Current.Request.Form.Get("txtSP").Length <= 8000)
        {
            hdSPDM.Value = HttpContext.Current.Request.Form.Get("txtSP");
        }

        #region 组织条件
        string where = " where 1=1";
        where += Tbx_OrderID.Text.Trim() == "" ? "" : " and V_ORDERDOC.Order_ID='" + Tbx_OrderID.Text.Trim() + "'";
        where += Tbx_LinkOrder.Text.Trim() == "" ? "" : " and V_ORDERDOC.Order_AID='" + Tbx_LinkOrder.Text.Trim() + "'";
        where += DDL_OrderFrom.Value == "" ? "" : " and V_ORDERDOC.ORDER_OFCODE IN (SELECT * FROM dbo.Split('" + DDL_OrderFrom.Value + "',','))";
        where += DDL_OrderCreater.Value == "" ? "" : " and V_ORDERDOC.ORDER_CREATER IN (SELECT * FROM dbo.Split('" + DDL_OrderCreater.Value + "',','))";
        where += Tbx_OrderCreateF.Text.Trim() == "" ? "" : " and V_ORDERDOC.ORDER_CREATEDATE>='" + Tbx_OrderCreateF.Text.Trim() + "'";
        where += Tbx_OrderCreateT.Text.Trim() == "" ? "" : " and V_ORDERDOC.ORDER_CREATEDATE<='" + Tbx_OrderCreateT.Text.Trim() + "'";
        where += Tbx_CustomerCode.Text.Trim() == "" ? "" : " and V_ORDERDOC.ORDER_CUSTOMERCODE in (select * from dbo.Split('" + Tbx_CustomerCode.Text.Trim() + "',','))";
        where += DDL_tradetype.Value == "" ? "" : " and [PAYDETAIL].PD_DTCODE IN (SELECT * FROM dbo.Split('" + DDL_tradetype.Value + "',','))";
        where += DDL_PayType.Value == "" ? "" : " and [PAYDETAIL].PD_PAYTYPE IN (SELECT * FROM dbo.Split('" + DDL_PayType.Value + "',','))";
        where += Tbx_CheckDateF.Text.Trim() == "" ? "" : " and V_ORDERDOC.ORDER_CHECKDATE>='" + Tbx_CheckDateF.Text.Trim() + "'";
        where += Tbx_CheckDateT.Text.Trim() == "" ? "" : " and V_ORDERDOC.ORDER_CHECKDATE<='" + Tbx_CheckDateT.Text.Trim() + "'";
        where += DDL_Check.SelectedValue == "-1" ? "" : " and V_ORDERDOC.ORDER_CHECK=" + DDL_Check.SelectedValue;
        where += DDL_Acheck.SelectedValue == "-1" ? "" : " and V_ORDERDOC.ORDER_ACHECK=" + DDL_Acheck.SelectedValue;
        where += DDL_Send.SelectedValue == "-1" ? "" : " and V_ORDERDOC.ORDER_SEND=" + DDL_Send.SelectedValue;
        where += DDL_Clear.SelectedValue == "-1" ? "" : " and V_ORDERDOC.ORDER_CLEAR=" + DDL_Clear.SelectedValue;
        where += Tbx_SendDateF.Text.Trim() == "" ? "" : " and V_ORDERDOC.ORDER_SENDDATE>='" + Tbx_SendDateF.Text.Trim() + "'";
        where += Tbx_SendDateT.Text.Trim() == "" ? "" : " and V_ORDERDOC.ORDER_SENDDATE<='" + Tbx_SendDateT.Text.Trim() + "'";
        where += DDL_Checker.Value == "" ? "" : " and V_ORDERDOC.ORDER_CHECKER IN (SELECT * FROM dbo.Split('" + DDL_Checker.Value + "',','))";
        where += DDL_aChecker.Value == "" ? "" : " and V_ORDERDOC.ORDER_ACHECKER IN (SELECT * FROM dbo.Split('" + DDL_aChecker.Value + "',','))";
        where += DDL_Sender.Value == "" ? "" : " and V_ORDERDOC.ORDER_SENDER IN (SELECT * FROM dbo.Split('" + DDL_Sender.Value + "',','))";
        where += DDL_Clearer.Value == "" ? "" : " and V_ORDERDOC.ORDER_ACHECKER IN (SELECT * FROM dbo.Split('" + DDL_Clearer.Value + "',','))";
        where += Tbx_AcheckDateF.Text.Trim() == "" ? "" : " and V_ORDERDOC.ORDER_ACHECKDATE>='" + Tbx_AcheckDateF.Text.Trim() + "'";
        where += Tbx_AcheckDateT.Text.Trim() == "" ? "" : " and V_ORDERDOC.ORDER_ACHECKDATE<='" + Tbx_AcheckDateT.Text.Trim() + "'";
        where += Tbx_ClearDateF.Text.Trim() == "" ? "" : " and V_ORDERDOC.BYZD9>='" + Tbx_ClearDateF.Text.Trim() + "'";
        where += Tbx_ClearDateT.Text.Trim() == "" ? "" : " and V_ORDERDOC.BYZD9<='" + Tbx_ClearDateT.Text.Trim() + "'";
        where += DDL_HDFK.SelectedValue == "-1" ? "" : " and V_ORDERDOC.ORDER_APAY=" + DDL_HDFK.SelectedValue;
        where += DDL_QueHuo.SelectedValue == "-1" ? "" : " and isnull(V_ORDERDOC.BYZD25,0)='" + DDL_QueHuo.SelectedValue + "'";
        where += DDL_ZF.SelectedValue == "-1" ? "" : " and V_ORDERDOC.ORDER_DELETE=" + DDL_ZF.SelectedValue;
        where += DDL_ORDER_STATETYPECODE.Value == "" ? "" : " and ORDER_STATETYPECODE IN (SELECT * FROM dbo.Split('" + DDL_ORDER_STATETYPECODE.Value + "',','))";
        where += txtUpStartTime.Text.Trim() == "" ? "" : " and T.CU_CHECKDATE>='" + txtUpStartTime.Text.Trim() + "'";
        where += txtUpEndTime.Text.Trim() == "" ? "" : " and T.CU_CHECKDATE<='" + txtUpEndTime.Text.Trim() + "'";
        where += txtSP.Text.Trim() == "" ? "" : " and SHANGPIN.SPDM in (select * from dbo.Split('" + txtSP.Text.Trim() + "',','))";


        if (DDL_TuiHuo.SelectedValue == "0")
        {
            where += " and V_ORDERDOC.Order_ID not in (select RD_DOCID from [RETURNDOC])";
        }
        if (DDL_TuiHuo.SelectedValue == "1")
        {
            where += " and V_ORDERDOC.Order_ID  in (select RD_DOCID from [RETURNDOC])";
        }
        #endregion
        DataSet ds = new BLL.ReportBL.SKUStatistics().GetSKU(where, "", DDL_OrderFrom.Value, drpKW.SelectedValue, hdSPDM.Value, DDL_PayType.Value);
        if (ds.Tables[0].Rows.Count > 1)
        {

            if (pageIndex==1) //导出excel
            {
                DataTable2Excel(ds.Tables[0]);
            }

            DataView view = new DataView(ds.Tables[0], "SPDM<>''", "AMT DESC", DataViewRowState.CurrentRows);
            grdSKU.DataSource = view;
            grdSKU.DataBind();
            grdSKU.PageIndex = pageIndex;
            DataRow dr = ds.Tables[0].Select("SPDM=''")[0];
            grdSKU.FooterRow.Cells[5].Text = string.Format("{0:N0}", decimal.Parse(dr["QTY"].ToString()));
            grdSKU.FooterRow.Cells[6].Text = string.Empty;
            grdSKU.FooterRow.Cells[7].Text = string.Format("{0:N2}", decimal.Parse(dr["AMT"].ToString()));
            grdSKU.FooterRow.Cells[8].Text = string.Empty;
            grdSKU.FooterRow.Cells[10].Text = string.Format("{0:N0}", decimal.Parse(dr["SL"].ToString()));
            grdSKU.FooterRow.Cells[11].Text = string.Format("{0:N0}", decimal.Parse(dr["SL3"].ToString()));
            //grdSKU.FooterRow.Cells[12].Text = string.Format("{0:N2}", decimal.Parse(dr["PERIOD"].ToString()));
        }
    }
  
}
